package map_set.map.hash;

public class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    private Node[] arr = new Node[10];
    public int size = 0;
    public static final double DEFAULT_LOAD_FACTOR = 0.75f;

    public void push(int key, int val) {
        int index = key % arr.length;
        Node cur = arr[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        Node node = new Node(key, val);
        node.next = arr[index];
        arr[index] = node;
        size++;
        if (DEFAULT_LOAD_FACTOR <= (double) size / arr.length) {
            resize();
        }
    }

    private void resize() {
        Node[] newArr = new Node[arr.length * 2];
        for (Node node : arr) {
            Node cur = node;
            while (cur != null) {
                int newIndex = cur.key % newArr.length;
                Node next = cur.next;
                cur.next = newArr[newIndex];
                newArr[newIndex] = cur;
                cur = next;
            }
        }
        arr = newArr;
    }

    public int getVal(int key) {
        int index = key % arr.length;
        Node cur = arr[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
